package pe.upc.dsd.jjjar.metropolitano;

import java.util.ArrayList;
import java.util.List;

import pe.upc.dsd.jjjar.metropolitano.RutasInMapActivity.MapOverlay;
import pe.upc.dsd.jjjar.metropolitano.services.RequestMethod;
import pe.upc.dsd.jjjar.metropolitano.services.RestClient;
import pe.upc.dsd.jjjar.rest.informacion.Estacion;
import pe.upc.dsd.jjjar.rest.informacion.Response;
import pe.upc.dsd.jjjar.rest.recarga.Respuesta;

import android.app.AlertDialog;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Canvas;
import android.graphics.Point;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup.LayoutParams;
import android.widget.LinearLayout;

import com.google.android.maps.GeoPoint;
import com.google.android.maps.MapActivity;
import com.google.android.maps.MapController;
import com.google.android.maps.MapView;
import com.google.android.maps.Overlay;
import com.google.gson.Gson;
import com.google.gson.JsonParseException;

public class EstacionesActivity extends MapActivity {

	MapView mapView;
	MapController mc;
	GeoPoint p;

	List<GeoPoint> points = new ArrayList<GeoPoint>();

	private double lat = 0.1, lng = 0.1;

	class MapOverlay extends com.google.android.maps.Overlay {
		public static final int POSICION = 0;
		public static final int ESTACION = 1;

		private GeoPoint point;
		private int type;

		public MapOverlay(GeoPoint p, int type) {
			this.point = p;
			this.type = type;
		}

		@Override
		public boolean draw(Canvas canvas, MapView mapView, boolean shadow,
				long when) {
			super.draw(canvas, mapView, shadow);

			// ---translate the GeoPoint to screen pixels---
			Point screenPts = new Point();
			mapView.getProjection().toPixels(point, screenPts);

			// ---add the marker---
			if (type == POSICION) {
				Bitmap bmp = BitmapFactory.decodeResource(getResources(),
						R.drawable.pushpin_position);
				canvas.drawBitmap(bmp, screenPts.x - 15, screenPts.y - 42, null);
			} else {
				Bitmap bmp = BitmapFactory.decodeResource(getResources(),
						R.drawable.pushpin_estacion);
				canvas.drawBitmap(bmp, screenPts.x - 14, screenPts.y - 42, null);
			}
			return true;
		}

	}

	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.estaciones);

		mapView = (MapView) findViewById(R.id.mapView);
		LinearLayout zoomLayout = (LinearLayout) findViewById(R.id.zoom);
		View zoomView = mapView.getZoomControls();

		zoomLayout.addView(zoomView, new LinearLayout.LayoutParams(
				LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT));
		mapView.displayZoomControls(true);

		mc = mapView.getController();

		// Acquire a reference to the system Location Manager
		LocationManager locationManager = (LocationManager) this
				.getSystemService(Context.LOCATION_SERVICE);

		// Define a listener that responds to location updates
		LocationListener locationListener = new LocationListener() {
			public void onLocationChanged(Location location) {
				// Called when a new location is found by the network location
				// provider.
				// makeUseOfNewLocation(location);

				lat = location.getLatitude();
				lng = location.getLongitude();

				p = new GeoPoint((int) (lat * 1E6), (int) (lng * 1E6));

				mc.animateTo(p);
				mc.setZoom(17);

				MapOverlay mapOverlay = new MapOverlay(p, MapOverlay.POSICION);
				List<Overlay> listOfOverlays = mapView.getOverlays();
				listOfOverlays.clear();
				listOfOverlays.add(mapOverlay);

				// ---Add a location marker---
				RestClient client = new RestClient(
						Constantes.SERVER_ENDPOINT + "/Informacion/rest/info/estaciones/"
								+ lat + "/" + lng);
				try {
					client.Execute(RequestMethod.GET);
				} catch (Exception e) {

				}

				String response = client.getResponse();

				Gson gson = new Gson();
				Response responseObject = null;
				try{
					responseObject = gson.fromJson(response, Response.class);
				}catch(JsonParseException e){}
				
				
				if (responseObject != null) {
					final List<Estacion> estaciones = responseObject
							.getListEstacion();

					for (int i = 0; i < estaciones.size(); i++) {
						Estacion estacion = estaciones.get(i);
						p = new GeoPoint((int) (estacion.getPosicion()
								.getLatitud() * 1E6), (int) (estacion
								.getPosicion().getLongitud() * 1E6));
						mapOverlay = new MapOverlay(p, MapOverlay.ESTACION);
						listOfOverlays.add(mapOverlay);
					}


				} else {

					AlertDialog.Builder builder = new AlertDialog.Builder(
							EstacionesActivity.this);
					builder.setMessage(
							"Se produjo un error en la comunicacion con el WebService.")
							.setCancelable(false)
							.setPositiveButton("Yes",
									new DialogInterface.OnClickListener() {
										public void onClick(
												DialogInterface dialog, int id) {
											EstacionesActivity.this.finish();
										}
									})
							.setNegativeButton("No",
									new DialogInterface.OnClickListener() {
										public void onClick(
												DialogInterface dialog, int id) {
											dialog.cancel();
										}
									});
					AlertDialog alert = builder.create();

				}

				mapView.invalidate();

			}

			public void onStatusChanged(String provider, int status,
					Bundle extras) {
				System.out.println("Status changed");

			}

			public void onProviderEnabled(String provider) {
				System.out.println("Provider Enabled");
			}

			public void onProviderDisabled(String provider) {
				System.out.println("Provider Disabled");
			}
		};

		// Register the listener with the Location Manager to receive location
		// updates
		locationManager.requestLocationUpdates(
				LocationManager.NETWORK_PROVIDER, 0, 0, locationListener);

	}

	public void refreshPosition() {

		LocationManager locationManager = (LocationManager) this
				.getSystemService(Context.LOCATION_SERVICE);
		// locationManager.

	}

	@Override
	protected boolean isRouteDisplayed() {
		return false;
	}

	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		MenuInflater inflater = getMenuInflater();
		inflater.inflate(R.menu.estaciones, menu);
		return true;
	}

	@Override
	public boolean onOptionsItemSelected(MenuItem item) {
		// Handle item selection
		switch (item.getItemId()) {
		case R.id.refresh:
			refreshPosition();
			return true;
		case R.id.help:
			// showHelp();
			return true;
		default:
			return super.onOptionsItemSelected(item);
		}
	}

	public void insertPin() {

		// String coordinates[] = {"1.352566007", "103.78921587"};
		double lat = this.lat - 0.100000;
		double lng = this.lng - 0.100000;

		p = new GeoPoint((int) (lat * 1E6), (int) (lng * 1E6));

		// ---Add a location marker---
		MapOverlay mapOverlay = new MapOverlay(p, MapOverlay.ESTACION);
		List<Overlay> listOfOverlays = mapView.getOverlays();
		// listOfOverlays.clear();
		listOfOverlays.add(mapOverlay);

		mapView.invalidate();

	}

}
